var TeacherTable = {
    cache: "",
    id:"teacherTable",
    seItem: null,		//选中的条目
    me : "",
    href: Feng.ctxPath + "/teacher/allParam"//教师管理url
};

/**
 * 初始化整个表格
 */
TeacherTable.init = function(){
    var defaultColunms = this.initColumn();
    var bstable = new BSTable(TeacherTable.id,TeacherTable.href,defaultColunms);
    bstable.setData({});
    this.me = bstable.init();
};
/**
 * 初始化表格的列
 */
TeacherTable.initColumn = function(){
    var columns = [
        {title: '序号',align: 'center',valign: 'middle',
            formatter: function indexFormatter(value, row, index) {//在表格前加上序号
                return index+1;
            }},
        {
            title: '头像', field: 'teacherImg', align: 'center', valign: 'middle',
            formatter: function(value,row,index){
                var imgUrl = Feng.ctxPath + "/img/logo_b.png";
                if (value) {
                    imgUrl = Feng.ctxPath + "/file/getImage/" + value;
                }
                return '<img style="width: 100px;height: 100px;" onclick="showPic(\'' + value + '\');" src="' + imgUrl + '" class="img-rounded" >';
            }},
        {title: '登录账号',field: 'username',align: 'center',valign: 'middle'},
        {title: '教师编号',field: 'teacherNumber',align: 'center',valign: 'middle'},
        {title: '姓名',field: 'truename',align: 'center',valign: 'middle'},
        {title: '性别',field: 'sex',align: 'center',valign: 'middle',
            formatter:function(value,row,index){
                if (value === "1") {
                    return "男";
                } else if (value === "2") {
                    return "女";
                }
            }},
        {title: '手机号码',field: 'phone',align: 'center',valign: 'middle'},
        {title: '教师类型',field: 'roleName',align: 'center',valign: 'middle'},
        {title: '所属机构', field: 'organization', align: 'center', valign: 'middle'},
        {title: '邮箱', field: 'email', align: 'center', valign: 'middle'},
       /* {title: '创建时间',field: 'createDate',align: 'center',valign: 'middle'},
        {title: '最后更新时间',field: 'updateDate',align: 'center',valign: 'middle'},*/
        {title: '状态',field: 'userState',align: 'center',valign: 'middle',
            formatter:function (value,row,index) {
                if (value === "1") {
                    return "正常";
                } else if (value === "2") {
                    return "锁定";
                }
            }},
        {title: '操作',field: '#',align: 'center',valign: 'middle',formatter:operateFormatter,events:{
            'click .edit': function (e, value, row, index) {
                editBtn(row.id);
            } ,
            'click .delete':function(e,value,row,index){
                deleteBtn(row.id,row.username);
            }
        }
        }];
    return columns;
};

/**
 * 操作按钮显示
 * @returns {string}
 */
function operateFormatter() {
    var e = '<button class="btn btn-primary btn-xs edit"  title="编辑"><i class="glyphicon glyphicon-pencil"></i></button>&nbsp;&nbsp;';
    var f = '<button class="btn btn-danger btn-xs delete"  title="删除"><i class="glyphicon glyphicon-trash"></i></button>&nbsp;&nbsp;';
    return e + f;
}

/**
 * 点击看大图
 * @param imgName
 */
function showPic(imgName) {
    layer.photos({
        photos: {
            "title": "banner图片", //相册标题
            "id": 123, //相册id
            "start": 0, //初始显示的图片序号，默认0
            "data": [   //相册包含的图片，数组格式
                {
                    "alt": "banner图片",
                    "pid": 666, //图片id
                    "src": Feng.ctxPath + "/file/getImage/" + imgName, //原图地址
                    "thumb": Feng.ctxPath + "/file/getImage/" + imgName //缩略图地址
                }
            ]
        },
        anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

/**
 * 点击搜索按钮
 * @returns
 */
function clickSearch() {
    var queryData = {};
    var val_search_teacherName = $("#txt_search_teacherName").val();

    if (val_search_teacherName !== null || val_search_teacherName !== "") {
        queryData['truename'] = val_search_teacherName;
    }
    TeacherTable.me.destroy(queryData);
    // TeacherTable.me.refresh({query: queryData});
}

/**
 * 点击添加按钮时，跳转到新增页面
 */
$("#btn_add").on("click",function () {
    window.location.href = Feng.ctxPath+"/teacher/info/page";
});

/**
 * 点击导入按钮时，弹出导入框
 */
$("#btn_excel_import").on("click", function () {
    layer.open({
        type: 1,
        title: '导入教师',
        skin: 'layui-layer-lan', //加上边框
        area: ['470px', '300px'],//宽高
        content: TeacherTable.cache,
        success: function (layero, index) {
            //层弹出成功后回调方法
            TeacherTable.excelInput();
        },
        maxmin: true,
        scrollbar: false,
        btn: ['关闭'],
        btnAlign: 'r',  //默认值
        yes: function (index, layero) {
            layer.close(index); //如果设定了yes回调，需进行手工关闭
            $("#importMsg").hide();
        },
        cancel: function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
            $("#importMsg").hide();
        }
    });
});

/**
 * excel导入教师
 */
TeacherTable.excelInput = function(){
    $("#file_excel").uploadify({
        height        : 30,
        swf           : Feng.ctxPath+'/js/assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : Feng.ctxPath+'/teacher/excel/input/?ver='+Math.random(),
        width         : 200,
        // wmode         : 'transparent',
        fileObjName   : 'file',
        fileTypeExts: '*.xlsx;*.xls;', //文件后缀限制 默认：'*.
        // fileSizeLimit: '20480KB', //文件大小限制 0为无限制 默认KB
        queueSizeLimit :1,
        multi: false,
        buttonText    : '导入教师信息', //按钮文字
        removeCompleted: false, //上传成功后的文件，是否在队列中自动删除
        overrideEvents: ['onSelectError', 'onUploadSuccess', 'onUploadError'],//重写事件
        //选择关闭事件
        // onDialogClose:function () {},
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            Feng.error(msgText);
        },

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        ////文件上传成功后的回掉方法
        'onUploadSuccess':function (file, data, response) {
            data = JSON.parse(data);
            if (data.success) {
                $("#importMsg").text("导入教师信息成功").show();
                TeacherTable.me.refresh();
            } else if (data.code === 2) {
                $("#importMsg").text(data.msg).show();
            } else {
                $("#importMsg").text("导入教师信息失败").show();
            }
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            $("#importMsg").hide();
            Feng.error("上传出现异常，请重新上传" + errorString);
        }

    });

};


/**
 * 点击编辑按钮时，跳出用户详情对话框
 * @returns
 */
function editBtn(uid){
    //window.location.href=Feng.ctxPath+"/teacher/info/page?id="+uid;
    var index = layer.open({
        type: 1,
        title: '编辑教师基本信息',
        skin: 'layui-layer-lan',
        area: [TeacherInfoDlg.width,'auto'],
        content: TeacherInfoDlg.cache,
        success: function(layero, index){
            //层弹出成功后回调方法
            TeacherInfoDlg.renderAdd();
            TeacherInfoDlg.teacherDetail(uid);
        },
        maxmin:true,
        scrollbar: false,
        btn:['保存','关闭'],
        btnAlign: 'r',  //默认值
        yes:function (index,layero) {
            TeacherInfoDlg.editSubmit();
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        },btn2:function (index) {
            layer.close(index);
        },
        cancel:function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
        }
    });
    layer.full(index);
    TeacherInfoDlg.currentLayerIndex = index;
}

/**
 * 删除删除教师
 * @param uid 用户的id
 * @returns
 */
function deleteBtn(uid,deleteName){
    layer.confirm('是否删除教师:'+deleteName, {icon: 10, title:'是否删除教师?'}, function(index){
        var ajax = new $ax(Feng.ctxPath + "/teacher/deleteById", function(data){
            if (data.success){
                Feng.success("删除成功!");
                // TeacherTable.init(1);
                TeacherTable.me.refresh();
                layer.close(index);
            }else if(data.code === 2){
                Feng.fail(data.msg);
            }else{
                Feng.fail("删除失败!");
            }
        },function(data){
            Feng.error("删除失败!");
        });
        ajax.set("id",uid);
        ajax.start();
    });
}

/**
 * 初始化新增弹出框
 */
TeacherTable.initTeacherDialog = function () {
    //加载模板文件下载连接
    $("#excelDownload").attr("href", "http://" + window.location.host + "/child/teacher/excel/download/");
    $("#importMsg").hide();
    this.cache = $("#teacherDialog").html();
    $("#teacherDialog").html('');
};

$(function(){
    TeacherTable.init(1);
    // TeacherTable.initTeacherDialog();
    TeacherInfoDlg.init();
});

